//
//  TSRechargeInfoViewController.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/6.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import HandyJSON

protocol TSRechargeInfoViewControllerDelegate : NSObjectProtocol {
    func completeRecharge()
}

class TSRechargeInfoViewController: TSBaseViewController {
    
    weak var delegate : TSRechargeInfoViewControllerDelegate? = nil
    var tableView : UITableView!
    var model : TSRechargeModel? = nil
    
    lazy var footerView : UIView = {
        let footer = UIView.init(frame: CGRect(x: 0, y: 0, width: Int(SCREEN_WIDTH), height: 30+48+30))
        footer.backgroundColor = WHITE_COLOR
        
        let commitBtn = UIButton.init(type: .system)
        commitBtn.setTitle("提交", for: .normal)
        commitBtn.setTitleColor(WHITE_COLOR, for: .normal)
        commitBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        commitBtn.backgroundColor = BASE_PURPLE_COLOR
        commitBtn.layer.cornerRadius = 24
        commitBtn.layer.masksToBounds = true
        commitBtn.addTarget(self, action: #selector(commitAction), for: .touchUpInside)
        footer.addSubview(commitBtn)
        commitBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(30)
            make.size.equalTo(CGSize(width: SCREEN_WIDTH*0.682, height: 48))
        }
        
        return footer
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavigationTitle(title: "充值")
        configViews()
        requestDatas()
    }
    
    @objc func commitAction() {
        IQKeyboardManager.shared().resignFirstResponder()
        NotificationCenter.default.post(name: .TSRechargeCommitNotification, object: nil)
    }

}

// MARK: - TSRechargeConfirmInfoTableViewCellDelegate
extension TSRechargeInfoViewController : TSRechargeConfirmInfoTableViewCellDelegate {
    
    func fitToCommit(usdt: String, name: String) {
        commitRecharge(money: usdt, ustdname: name)
    }
}

//MARK: - UITableViewDelegate
extension TSRechargeInfoViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 44))
        header.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        
        let titleLabel = UILabel.init()
        titleLabel.attributedText = setupSectionHeaderContent(section: section)
        header.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(12)
        }
        
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.001))
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}

//MARK: - UITableViewDataSource
extension TSRechargeInfoViewController : UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 1 : 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        
        var cell : UITableViewCell?
        
        if indexPath.section == 0 {
            var infoCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSRechargeInfoTableViewCell.self)) as? TSRechargeInfoTableViewCell
            
            if infoCell == nil {
                infoCell = TSRechargeInfoTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSRechargeInfoTableViewCell.self))
            }
            
            if self.model != nil {
                infoCell?.setupCell(model: self.model!)
            }
            
            cell = infoCell
            
        } else {
            
            if indexPath.row == 0 {
                
                var inputCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSRechargeConfirmInfoTableViewCell.self)) as? TSRechargeConfirmInfoTableViewCell
                
                if inputCell == nil {
                    inputCell = TSRechargeConfirmInfoTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSRechargeConfirmInfoTableViewCell.self))
                }
                
                let rate = NSString.init(string: self.model?.ustd ?? "")
                inputCell?.setupRate(rate: rate.doubleValue)
                
                inputCell?.delegate = self
                
                cell = inputCell
                
            } else {
                
                var autoHeightCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSAutoHeightTableViewCell.self)) as? TSAutoHeightTableViewCell
                
                if autoHeightCell == nil {
                    autoHeightCell = TSAutoHeightTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSAutoHeightTableViewCell.self))
                }
                
                autoHeightCell?.setupLabel(content: getInfoContent(), topInset: 20, textColor: "#686868", fontSize: 13)
                
                cell = autoHeightCell
            }
            
        }
        
        return cell!
    }
}

//MARK: - Network Request
extension TSRechargeInfoViewController {
    
    // 获取汇率相关信息
    func requestDatas() {
        
        TSNetworkManager.request(TMSNetworkTools.rechargeUsdt, showHUD: true, success: { (data) in
            
            CBToast.hiddenToastAction()
            let responseDic = data as? NSDictionary
            let model = TSRechargeModel.deserialize(from: responseDic)
            self.model = model
            self.tableView.reloadData()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    // 充值
    func commitRecharge(money:String, ustdname:String) {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.requestForRecharge(money: money, ustdname: ustdname), showHUD: true, success: { (data) in
            
            CBToast.showToastAction(message: "提交成功，等待审核")
            self.requestUserInfo()
            
        }) { (error) in
            
            CBToast.hiddenToastAction()
        }
    }
    
    // 刷新个人信息
    func requestUserInfo() {
        
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: false, success: { (data) in
            
            CBToast.hiddenToastAction()
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            CBToast.showToastAction(message: "充值成功")
            self.tableView.reloadData()
            
            if self.delegate != nil {
                self.delegate?.completeRecharge()
            }
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
}

//MARK: - Initialize
extension TSRechargeInfoViewController {
    
    func configViews() {
        
        tableView = UITableView.init(frame: .zero, style: .grouped)
        tableView.backgroundColor = WHITE_COLOR
        tableView.delegate = self;
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.tableFooterView = footerView
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableView.automaticDimension
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
        }
        
        if #available(iOS 11, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    func getInfoContent() -> String {
        return "充值步骤：\n1.在火币网购买USDT。\n2.从法币账户转入币币账户。\n3.点击提币输入USDT复制彩金彩钱包地址，输入提币数量 确定。\n4.后台提交对应的USDT数量，就会有折合人民币提示，输入姓名提交。\n重要提示：请每次充值时务必核对最新的二维码钱包地址信息！平台会不定期更换新的二维码钱包地址。如因本人原因造成的损失平台概不负责！"
    }
    
    func setupSectionHeaderContent(section:Int) -> NSAttributedString {
        
        let attributed : NSMutableAttributedString!
        
        if section == 0 {
            let str = "收款信息"
            attributed = NSMutableAttributedString.init(string: str)
            attributed.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.hexadecimalColor(hexadecimal: "#282828"), NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16, weight: .medium)], range: NSMakeRange(0, str.count))
        } else {
            var str = "入款确认信息"
            if self.model?.ustd?.count ?? 0 > 0 {
                str = str+String.init(format: "（汇率：%@）", self.model!.ustd!)
            }
            let nsStr = NSString(string: str)
            attributed = NSMutableAttributedString.init(string: str)
            attributed.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.hexadecimalColor(hexadecimal: "#282828"), NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16, weight: .medium)], range: NSMakeRange(0, str.count))
            
            attributed.addAttributes([NSAttributedString.Key.foregroundColor:BASE_RED_COLOR], range: nsStr.range(of: "7.1"))
            
        }
        
        return attributed?.copy() as! NSAttributedString
    }
}
